package com.example.flowermall.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.*;

public class WechatSignUtils {

    public static String sign(Map<String, String> params, String apiKey, String signType) throws Exception {
        // 1. 参数排序并拼接
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder stringA = new StringBuilder();
        for (String key : keys) {
            String value = params.get(key);
            if (value != null && !value.isEmpty() && !key.equals("sign")) {
                stringA.append(key).append("=").append(value).append("&");
            }
        }
        stringA.append("key=").append(apiKey);

        // 2. 生成签名
        if ("HMAC-SHA256".equals(signType)) {
            Mac sha256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes("UTF-8"), "HmacSHA256");
            sha256.init(secretKey);
            byte[] hash = sha256.doFinal(stringA.toString().getBytes("UTF-8"));
            return bytesToHex(hash).toUpperCase();
        } else { // MD5
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] hash = md5.digest(stringA.toString().getBytes("UTF-8"));
            return bytesToHex(hash).toUpperCase();
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }
}
